package com.vp.org.web.servlet;

import com.vp.org.dao.AdminInfoDao;
import com.vp.org.dao.impl.AdminInfoDaoImpl;
import com.vp.org.pojo.AdminInfo;
import com.vp.org.web.base.BaseServlet;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

@WebServlet("/admins")
public class AdminServlet extends BaseServlet {

    private AdminInfo adminInfo = null;
    private AdminInfoDao adminInfoDao = null;

    public void deleteAdmin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String admin = request.getParameter("admin");

        adminInfo = new AdminInfo();
        adminInfoDao = new AdminInfoDaoImpl();

        adminInfo.setAdmin(admin);

        if (adminInfoDao.deleteAdmin(adminInfo) > 0) {
            // 删除成功
           /* request.setAttribute("adminSuccess",1);
            request.getRequestDispatcher("admin/adminQuery.jsp").forward(request,response); */
            response.sendRedirect("http://localhost:8080/admins?method=findByPage&pageIndex=1");
        } else {
            // 删除失败
            response.sendRedirect("/admin/error.jsp");
        }

    }

    public void updateAdmin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        adminInfo = new AdminInfo();
        adminInfoDao = new AdminInfoDaoImpl();

        // 用BeanUtils封装
        try {
            BeanUtils.populate(adminInfo, map);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }


        if (adminInfoDao.updateAdmin(adminInfo) > 0) {
            // 修改成功

            /*request.setAttribute("adminSuccess",1);
            request.getRequestDispatcher("/admin/adminQuery.jsp").forward(request,response);*/
            // 地址重定向
             response.sendRedirect("/admin/adminQuery.jsp");

        } else {
            // 修改失败
            response.sendRedirect("/admin/error.jsp");
        }

    }

    public void findByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //接收用户点击的上一页，下一页或者是指定的页数
        int pageIndex = Integer.parseInt(request.getParameter("pageIndex"));

        adminInfoDao = new AdminInfoDaoImpl();

        // 供应商分页查询,默认第一页
        request.getSession().setAttribute("admins", adminInfoDao.queryAdmin(pageIndex));
        // 供应商分页总页数
        request.getSession().setAttribute("adminPage", adminInfoDao.adminPage());
        // 供应商存储是第几页
        request.getSession().setAttribute("countPage",pageIndex);

        // 地址重定向
        response.sendRedirect("admin/adminQuery.jsp");
    }
}
